package org.brisling.common.crypt.strategy.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

import org.brisling.common.crypt.strategy.base.AbstractCrypt;
import org.brisling.common.crypt.strategy.inf.crypt;


/**
 * 
 * <p>Title: AESCryptImpl</p>
 * <p>Description: AES加密解密实现类</p>
 * <p>Company: tongking</p>
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2017年5月18日 下午3:31:26
 */
public class AESCryptImpl extends AbstractCrypt implements crypt{

	final Base64.Decoder decoder = Base64.getDecoder();
	final Base64.Encoder encoder = Base64.getEncoder();
	
	public AESCryptImpl() {
		super("AES");
		// TODO Auto-generated constructor stub
	}

	@Override
	public String encrypt(String plain, Key key) {
		// TODO Auto-generated method stub
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
        byte[] byte_encode = null;
        byte [] byte_AES = null;
		try {
			byte_encode = plain.getBytes("utf-8");
			byte_AES = cipher.doFinal(byte_encode);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //9.根据密码器的初始化方式--加密：将数据加密
        ;
      //10.将加密后的数据转换为字符串
        //这里用Base64Encoder中会找不到包
        //解决办法：
        //在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
        String AES_encode=new String(encoder.encode(byte_AES));
        
      //11.将字符串返回
        return AES_encode;
	}

	@Override
	public String decrypt(String data, Key key) {
		// TODO Auto-generated method stub
		
		String AES_decode = null;
		try {
			cipher.init(Cipher.DECRYPT_MODE, key);
			 byte [] byte_content= decoder.decode(data);
			 
		        /*
		         * 解密
		         */
		     byte [] byte_decode=cipher.doFinal(byte_content);
		     
		     
		     AES_decode =new String(byte_decode,"utf-8");
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
		
        return AES_decode;
	}

}
